package android_rteditor.customsortricheditor;

import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android_rteditor.customsortricheditor.editor.EditorDiplomat;
import android_rteditor.customsortricheditor.event.EventCenter;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final File PHOTO_DIR = new File(
            Environment.getExternalStorageDirectory() + "/DCIM/Camera");

    public static final int REQUEST_CODE_PICK_IMAGE = 1023;
    public static final int REQUEST_CODE_CAPTURE_CAMEIA = 1022;

    private File mCurrentPhotoFile;// 照相机拍照得到的图片

    private ImageView photoBtn;
    private ImageView imageBtn;
    private ImageView todoBtn;
    private ImageView voiceBtn;

    private EditorDiplomat editorDiplomat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        photoBtn = (ImageView) findViewById(R.id.format_bar_button_photo);
        imageBtn = (ImageView) findViewById(R.id.format_bar_button_image);
        todoBtn = (ImageView) findViewById(R.id.format_bar_button_todo);
        voiceBtn = (ImageView) findViewById(R.id.format_bar_button_voice);
        photoBtn.setOnClickListener(this);
        imageBtn.setOnClickListener(this);
        todoBtn.setOnClickListener(this);
        voiceBtn.setOnClickListener(this);
        RichEditor richEditor = (RichEditor) findViewById(R.id.richEditor);
        editorDiplomat = richEditor.getEditorDiplomat();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleRichImageDelete(EventCenter.ImageDeleteEvent event) {
        if (event == null) {
            return;
        }

        editorDiplomat.removeRichImage(event.mRichImage);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleRichAudioDelete(EventCenter.AudioDeleteEvent event) {
        if (event == null) {
            return;
        }

        editorDiplomat.removeRichAudio(event.mRichAudio);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA) {
            editorDiplomat.insertImage(mCurrentPhotoFile.getAbsolutePath());

        } else if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            try {
                Uri uri = data.getData();
                final String absolutePath = getAbsolutePath(this, uri);
                if (!TextUtils.isEmpty(absolutePath)) {
                    editorDiplomat.insertImage(absolutePath);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取相册图片的绝对路径
     *
     * @param context context
     * @param uri     uri
     * @return url
     */
    public String getAbsolutePath(final Context context, final Uri uri) {
        if (null == uri) {
            return null;
        }
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.format_bar_button_photo:
                openCamera();
                break;
            case R.id.format_bar_button_image:
                openAlbum();
                break;
            case R.id.format_bar_button_todo:
                editorDiplomat.insertCheckbox();
                break;
            case R.id.format_bar_button_voice:
                editorDiplomat.insertAudio();
                break;
            default:
                break;
        }
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        try {
            PHOTO_DIR.mkdirs();// 创建照片的存储目录
            mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());// 给新照的照片文件命名
            final Intent intent = getTakePickIntent(mCurrentPhotoFile);
            startActivityForResult(intent, REQUEST_CODE_CAPTURE_CAMEIA);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, REQUEST_CODE_PICK_IMAGE);
    }

    /**
     * 用当前时间给取得的图片命名
     */
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(date) + ".jpg";
    }

    public Intent getTakePickIntent(File f) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        return intent;
    }

}
